package com.zyh.scs.admin.utils;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zyh.scs.admin.api.constant.CodeSet;
import com.zyh.scs.admin.api.dto.fanWei.FanWeiQueryDto;
import com.zyh.scs.admin.api.entity.SysUser;
import com.zyh.scs.admin.api.utils.MD5Util;
import com.zyh.scs.admin.base.LaoSheFanWeiResponse;
import com.zyh.scs.admin.mapper.SysUserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * 泛微OA 接口请求工具类
 *
 * @author hwh
 */
@Slf4j
@Component
public class FanWeiReqUtil {

    @Value("${fanWei.apikey}")
    public String API_KEY;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 调用 列表查询 泛微总数
     *
     * @param url
     * @param dto
     * @return
     * @throws Exception
     */
    public LaoSheFanWeiResponse<JSONArray> queryReqAccount(String url, FanWeiQueryDto dto) {

        String ts = String.valueOf(System.currentTimeMillis());
        String key = MD5Util.MD5Encode(String.format("%s%s", API_KEY, ts), "UTF-8");

        url = String.format("%s?pageIndex=%s&pageSize=%s", url, dto.getPageIndex(), dto.getPageSize());

        log.info("[泛微OA接口请求数量] <<<<<< 开始调用，url: {}, header(key: {}, ts: {})",
                url, key, ts);
        HttpResponse response = HttpRequest.post(url)
                .header("content-type", "application/json;charset=UTF-8")
                .header("key", key)
                .header("ts", ts)
                // .body(data)
                .execute();
        log.info("[泛微OA接口请求数量] <<<<<< 调用完成，url: {}, header(key: {}), reqData: {}, {}",
                url, key, response.getStatus(), response.body());

        if (null == response) {
            log.info("[泛微OA接口请求数量] <<<<<< 响应数据为空");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        if (HttpStatus.HTTP_OK != response.getStatus()) {
            log.info("[泛微OA接口请求数量] <<<<<< 响应状态不成功, status: {}", response.getStatus());
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        String body = response.body();

        if (StrUtil.isEmpty(body)) {
            log.info("[泛微OA接口请求数量] <<<<<< 响应body为空");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        JSONObject jsonObject = JSONObject.parseObject(body);

        if (null == jsonObject) {
            log.info("[泛微OA接口请求数量] <<<<<< 响应body序列化失败");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        String code = jsonObject.getString("code");

        if (StrUtil.isEmpty(code) || !"SUCCESS".equals(code)) {
            log.info("[泛微OA接口请求数量] <<<<<< 响应code不成功, code: {}", code);
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        JSONObject dataObj = jsonObject.getJSONObject("data");

        if (null == dataObj) {
            log.info("[泛微OA接口请求数量] <<<<<< 响应data为空");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        String total = dataObj.getString("total");

        if (StrUtil.isEmpty(total)) {
            log.info("[泛微OA接口请求数量] <<<<<< 响应total为空");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getIsAdmin, 2)
                .orderByAsc(SysUser::getCreateTime)
                .last("limit 1"));
        sysUser.setDepartmentAccount(StrUtil.isNotBlank(total) ? total : null);
        sysUser.setUserPsnAccount(StrUtil.isNotBlank(total) ? total : null);
        sysUser.setUserZhyAccount(StrUtil.isNotBlank(total) ? total : null);

        return LaoSheFanWeiResponse.success("泛微同步数量成功");
    }


    /**
     * 调用 列表查询
     *
     * @param url
     * @param dto
     * @return
     * @throws Exception
     */
    public LaoSheFanWeiResponse<JSONArray> queryReq(String url, FanWeiQueryDto dto) {

        String ts = String.valueOf(System.currentTimeMillis());
        String key = MD5Util.MD5Encode(String.format("%s%s", API_KEY, ts), "UTF-8");

        url = String.format("%s?pageIndex=%s&pageSize=%s", url, dto.getPageIndex(), dto.getPageSize());

        log.info("[泛微OA接口请求] <<<<<< 开始调用，url: {}, header(key: {}, ts: {})",
                url, key, ts);
        HttpResponse response = HttpRequest.post(url)
                .header("content-type", "application/json;charset=UTF-8")
                .header("key", key)
                .header("ts", ts)
                // .body(data)
                .execute();
        log.info("[泛微OA接口请求] <<<<<< 调用完成，url: {}, header(key: {}), reqData: {}, {}",
                url, key, response.getStatus(), response.body());

        if (null == response) {
            log.info("[泛微OA接口请求] <<<<<< 响应数据为空");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        if (HttpStatus.HTTP_OK != response.getStatus()) {
            log.info("[泛微OA接口请求] <<<<<< 响应状态不成功, status: {}", response.getStatus());
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        String body = response.body();

        if (StrUtil.isEmpty(body)) {
            log.info("[泛微OA接口请求] <<<<<< 响应body为空");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        JSONObject jsonObject = JSONObject.parseObject(body);

        if (null == jsonObject) {
            log.info("[泛微OA接口请求] <<<<<< 响应body序列化失败");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        String code = jsonObject.getString("code");

        if (StrUtil.isEmpty(code) || !"SUCCESS".equals(code)) {
            log.info("[泛微OA接口请求] <<<<<< 响应code不成功, code: {}", code);
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        JSONObject dataObj = jsonObject.getJSONObject("data");

        if (null == dataObj) {
            log.info("[泛微OA接口请求] <<<<<< 响应data为空");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        JSONArray dataList = dataObj.getJSONArray("dataList");

        if (CollectionUtils.isEmpty(dataList)) {
            log.info("[泛微OA接口请求] <<<<<< 响应dataList为空");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        return LaoSheFanWeiResponse.successData(dataList);
    }

}